//
//  ViewController.m
//  EMEIJU_IOS
//
//  Created by Caesar on 16/9/6.
//  Copyright (c) 2016年 Caesar. All rights reserved.
//

#import "SecondViewController.h"
#import "AFHTTPSessionManager.h"
//ShareSDK头文件
#import <ShareSDK/ShareSDK.h>

@interface SecondViewController (){
    UIWebView *webView;
    NSUserDefaults *userDefaults;
    NSString *redirectString;
    NSString *titleString;
    NSString *summaryString;
    NSString *imageString;
    NSString *startURLString;
    NSString *shareURLString;
}

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    userDefaults=[[NSUserDefaults alloc] init];
    NSDictionary *dataDic=[userDefaults objectForKey:@"dataDic"];
    startURLString=[NSString stringWithFormat:@"http://www.fdcanet.com/index.php?app=agent&id=%@&act=new_articles&appid=1",dataDic[@"agent_id"]];
    redirectString=startURLString;
    NSLog(@"urlString:%@",redirectString);
    webView=(UIWebView *)[self.view viewWithTag:1201];
    [webView setScalesPageToFit:YES];
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:startURLString]];
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"agency_two" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
//    request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    webView.delegate=self;
    [self setRightShareItems];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 1.添加数据
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:redirectString]];
        [webView loadRequest:request];
        // 2.2秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        });
    }];
    [header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"松开进行刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"易美居正在帮你刷新,请稍候..." forState:MJRefreshStateRefreshing];
    webView.scrollView.mj_header = header;
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 1.添加数据
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:redirectString]];
    [webView loadRequest:request];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:startURLString]];
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"agency_two" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
//    request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

//从webview中拨打电话
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = request.URL;
    NSString *urlString=[url absoluteString];
    NSRange range1 = [urlString rangeOfString:@"/article/"];
    NSRange range6 = [urlString rangeOfString:@"act=house_map"];
    if(range1.length>0){
        if (![redirectString isEqualToString:urlString]) {
            [self setLeftButtonItems:YES];
            redirectString =urlString;
            NSLog(@"urlString==%@",urlString);
            [self getShareMessage];
        }
    }else if ([urlString isEqualToString:startURLString]){
        [self setLeftButtonItems:NO];
    }else{
        [self setLeftButtonItems:YES];
//        if(range6.length<=0){
            redirectString =urlString;
//        }
    }
    return YES;
}

- (void)getShareMessage
{
    NSString *jsonURL=[NSString stringWithFormat:@"%@&json=1",redirectString];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFHTTPSessionManager manager] GET:jsonURL parameters:nil success:^(NSURLSessionDataTask * __unused task, id JSON) {
        if (JSON) {
            NSDictionary *dataDic=JSON[@"data"];
            titleString=dataDic[@"title"];
            summaryString=dataDic[@"summary"];
            imageString=dataDic[@"image"];
            shareURLString=dataDic[@"link"];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"提示" message:@"JSON数据解析出错" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
    
}

- (void) webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidFinishLoad");
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"didFailLoadWithError:%@", error);
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)setRightShareItems{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton addTarget:self action:@selector(customizeShareContents:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:@"icon_share.png"] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)setLeftButtonItems:(BOOL)setImage{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (setImage) {
        leftButton.frame = CGRectMake(0, 0, 44, 44);
        [leftButton addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
        [leftButton setImage:[UIImage imageNamed:@"icon_back.png"] forState:UIControlStateNormal];
    }
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)goBack:(UIButton *)button
{
    if (webView.canGoBack) {
        [webView goBack];
    }
}

- (void)customizeShareContents:(UIButton *)button
{
    //1、构造分享内容
    //1.1、要分享的图片（以下分别是网络图片和本地图片的生成方式的示例）
    if (!titleString) {
        titleString=@"易美居";
    }
    if (!summaryString) {
        summaryString=@"中国人在美国都买什么样的房子";
    }
    if (!imageString) {
        imageString=@"http://www.fdcanet.com/data/files/mall/article/37/18439.jpg";
    }
    if (!shareURLString) {
        shareURLString=redirectString;
    }
    id<ISSCAttachment> remoteAttachment = [ShareSDKCoreService attachmentWithUrl:imageString];
    //    id<ISSCAttachment> localAttachment = [ShareSDKCoreService attachmentWithPath:[[NSBundle mainBundle] pathForResource:@"shareImg" ofType:@"png"]];
    
    //1.2、以下参数分别对应：内容、默认内容、图片、标题、链接、描述、分享类型
    id<ISSContent> publishContent = [ShareSDK content:summaryString
                                       defaultContent:nil
                                                image:remoteAttachment
                                                title:titleString
                                                  url:shareURLString
                                          description:nil
                                            mediaType:SSPublishContentMediaTypeNews];
    
    //1.3、自定义各个平台的分享内容(非必要)
    [self customizePlatformShareContent:publishContent];
    
    //1.4、自定义一个分享菜单项(非必要)
    
    //1.5、分享菜单栏选项排列位置和数组元素index相关(非必要)ShareTypeWeixiSession,ShareTypeWeixiTimeline,ShareTypeQQ,ShareTypeQQSpace,ShareTypeLine,ShareTypeFacebook,ShareTypeMail,ShareTypeSMS,ShareTypeLinkedIn,ShareTypeTwitter,ShareTypeSinaWeibo
    NSArray *shareList = [ShareSDK customShareListWithType:
                          SHARE_TYPE_NUMBER(ShareTypeWeixiSession),
                          SHARE_TYPE_NUMBER(ShareTypeWeixiTimeline),
                          SHARE_TYPE_NUMBER(ShareTypeWeixiFav),
                          SHARE_TYPE_NUMBER(ShareTypeQQ),
                          SHARE_TYPE_NUMBER(ShareTypeQQSpace),
                          SHARE_TYPE_NUMBER(ShareTypeLine),
                          SHARE_TYPE_NUMBER(ShareTypeFacebook),
                          SHARE_TYPE_NUMBER(ShareTypeMail),
                          SHARE_TYPE_NUMBER(ShareTypeSMS),
                          SHARE_TYPE_NUMBER(ShareTypeLinkedIn),
                          SHARE_TYPE_NUMBER(ShareTypeTwitter),
                          SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                          nil];
    
    //1+、创建弹出菜单容器（iPad应用必要，iPhone应用非必要）
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:self.view arrowDirect:UIPopoverArrowDirectionUp];
    
    //2、展现分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:shareList
                           content:publishContent
                     statusBarTips:NO
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                NSLog(@"=== response state :%zi ",state);
                                
                                //可以根据回调提示用户。
                                if (state == SSResponseStateSuccess)
                                {
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success"
                                                                                    message:nil
                                                                                   delegate:self
                                                                          cancelButtonTitle:@"OK"
                                                                          otherButtonTitles:nil, nil];
                                    [alert show];
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed"
                                                                                    message:[NSString stringWithFormat:@"Error Description：%@",[error errorDescription]]
                                                                                   delegate:self
                                                                          cancelButtonTitle:@"OK"
                                                                          otherButtonTitles:nil, nil];
                                    [alert show];
                                }
                            }];
}

- (void)customizePlatformShareContent:(id<ISSContent>)publishContent
{
    
    id<ISSCAttachment> localAttachment = [ShareSDKCoreService attachmentWithUrl:imageString];
    //定制QQ空间分享内容
    [publishContent addQQSpaceUnitWithTitle:titleString
                                        url:shareURLString
                                       site:nil
                                    fromUrl:nil
                                    comment:@"comment"
                                    summary:summaryString
                                      image:localAttachment
                                       type:@(4)
                                    playUrl:nil
                                       nswb:0];
    
    //定制邮件分享内容
    [publishContent addMailUnitWithSubject:titleString
                                   content:[NSString stringWithFormat:@"%@ %@",summaryString,shareURLString]
                                    isHTML:[NSNumber numberWithBool:YES]
                               attachments:@[localAttachment]
                                        to:nil
                                        cc:nil
                                       bcc:nil];
    
    //定制新浪微博分享内容
    
    [publishContent addSinaWeiboUnitWithContent:[NSString stringWithFormat:@"%@ %@",summaryString,shareURLString] image:localAttachment];
    
    [publishContent addFacebookWithContent:[NSString stringWithFormat:@"%@ %@",summaryString,shareURLString] image:localAttachment];
    
    [publishContent addSMSUnitWithContent:[NSString stringWithFormat:@"%@ %@",summaryString,shareURLString]];
    
    [publishContent addLineUnitWithContent:[NSString stringWithFormat:@"%@ %@",summaryString,shareURLString] image:nil];
    
}

@end
